package Data;

import static Main.Constants.DB_URL_SHUTDOWN;
import static Main.Constants.DB_URL_CREATE;
import static Main.Constants.DB_DRIVER;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Holds the connection to the database as a static field. Uses static methods
 * to create {@link java.sql.Statement} objects for the bokhandel database.
 * The database connection is specified in the {@link Main.Constants} class.
 * 
 * @author Rodrigo Acuna
 * 
 */

public class Database {

	private static Connection con = null;
	
	public static void setConnection(Connection connection) {
		Database.con = connection;
	}
	
	/**
	 * Creates a connection to the database. The method uses the constants
	 * {@link main.Constants#DB_URL_CREATE} to determine which database to
	 * connect to. Writes a log remark in the console.
	 * @return 
	 * 
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection createConnection() throws ClassNotFoundException,
			SQLException {
		Class.forName(DB_DRIVER);
		System.out.println("Kopplar upp databas mot: " + DB_URL_CREATE);
		con = DriverManager.getConnection(DB_URL_CREATE);
		return con;
	}
	
	/**
	 * Creates a new {@link java.sql.Statement} object using the connection held
	 * by this class. If a connection does not exist, then it is automatically
	 * created by this method.
	 * 
	 * @return the new {@link java.sql.Statement} object
	 * @throws SQLException
	 *             thrown if the database connection throws an SQL exception.
	 * @throws ClassNotFoundException
	 *             thrown if we try to load a required JDBC driver that cannot be found.
	 */
	public static Statement createStatement() throws SQLException,
			ClassNotFoundException {
		if (con == null) {
			createConnection();
		}
		System.out.println("create statement");
		return con.createStatement();
	}
	
	/**
	 * Closes the connection to the database, that is held by this class.The method 
	 * uses the constants {@link main.Constants#DB_URL_SHUTDOWN}. An
	 * exception is always thrown by Apache Derby, so the exception is ignored.
	 * Writes a log remark in the console.
	 */
	public static void closeConnection() {
		try {
			DriverManager.getConnection(DB_URL_SHUTDOWN);
		} catch (SQLException e) { // ignored - always happening
			System.out.println("Stänger uppkopplingen mot databasen på följande adress: "
					+ DB_URL_SHUTDOWN);
		}
	}
}
